package com.neusoft.lohas.modules.shop.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.Utils;
import com.neusoft.lohas.modules.ivm.dao.merchant.ActivityPosterDao;
import com.neusoft.lohas.modules.ivm.dao.merchant.MerchantClauseDao;
import com.neusoft.lohas.modules.ivm.dao.merchant.ReceiptTimeDao;
import com.neusoft.lohas.modules.ivm.dao.merchant.TimeSlotDao;
import com.neusoft.lohas.modules.ivm.dao.order.OrderDao;
import com.neusoft.lohas.modules.ivm.dao.order.UserAddressDao;
import com.neusoft.lohas.modules.ivm.dao.product.ProductClassifyDao;
import com.neusoft.lohas.modules.ivm.dao.product.ProductDao;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityProduct;
import com.neusoft.lohas.modules.ivm.entity.merchant.ActivityPoster;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.merchant.MerchantClause;
import com.neusoft.lohas.modules.ivm.entity.merchant.ReceiptTime;
import com.neusoft.lohas.modules.ivm.entity.order.ShoppingCart;
import com.neusoft.lohas.modules.ivm.entity.order.UserAddress;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.enums.order.OrderTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayStatusEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayTypeEnum;
import com.neusoft.lohas.modules.ivm.service.business.ActivityProductService;
import com.neusoft.lohas.modules.shop.dao.ShoppingCartDao;
import com.neusoft.lohas.modules.sys.entity.User;

@Component
@Transactional(readOnly = true)
public class ShopService extends BaseService{

	@Autowired
	private ProductDao productDao;
	@Autowired
	private ActivityPosterDao activityPosterDao;
	@Autowired
	private MerchantClauseDao merchantClauseDao;
	@Autowired
	private ShoppingCartDao shoppingCartDao;
	@Autowired
	private UserAddressDao userAddressDao;
	@Autowired
	private ReceiptTimeDao receiptTimeDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private TimeSlotDao timeSlotDao;
	@Autowired
	private ProductClassifyDao productClassifyDao;
	@Autowired
	private ActivityProductService activityProductService;
	
	/**
	 * 商品列表
	 * @param sid
	 * @param product
	 * @return
	 */
	public List<Product> findProducts(String sid, Product product, String shopModel) {
		String sql = "select distinct pro.* from ivm_product pro "
					+" left join ivm_relationship_product_classify rel on pro.id = rel.product_id "
					+" left join ivm_product_classify cla on cla.id=rel.classify_id and cla.del_flag='0' "
					+" where pro.del_flag='0' "
					+" and pro.merchant_id='"+sid+"' and pro.open_state='1'";
		if (StringUtils.isNotEmpty(product.getName())){
			sql += " and pro.name like '%"+product.getName()+"%'";
		}
		if (product.getClassify()!=null && StringUtils.isNotBlank(product.getClassify().getId()) && shopModel.equals("merchant")) {
			sql += " and pro.classify_id = '"+product.getClassify().getId()+"'";
		}
		if (product.getClassifyIdList().size()>0 && shopModel.equals("classify")) {
			String classifyIds = Utils.ListToString(product.getClassifyIdList(), null);
			if(classifyIds!=null)
				sql += " and (rel.classify_id in ("+classifyIds+") or cla.parent_id in ("+classifyIds+"))";
		}
		sql += " order by pro.sort ";
		return productDao.findBySql(sql, new Parameter(), Product.class);
	}
	
	/**
	 * 获取小店公告
	 * @param posterId
	 * @return
	 */
	public ActivityPoster getActivityPosterById(String posterId){
		return activityPosterDao.get(posterId);
	}
	
	/**
	 * 获取配送规则
	 * @param clauseId
	 * @return
	 */
	public MerchantClause getMerchantClauseById(String clauseId){
		return merchantClauseDao.get(clauseId);
	}
	
	/**
	 * 获取当前我的购物车
	 * @param userId
	 * @return
	 */
	public List<ShoppingCart> findShoppingCarts(String merchantId, String userId){
		DetachedCriteria dc = shoppingCartDao.createDetachedCriteria();
		dc.add(Restrictions.eq(ProductClassify.FIELD_DEL_FLAG, ProductClassify.DEL_FLAG_NORMAL));
		dc.add(Restrictions.eq("merchant.id", merchantId));
		dc.add(Restrictions.eq("user.id", userId));
		dc.addOrder(Order.asc("createDate"));
		return shoppingCartDao.find(dc);
	}
	
	@Transactional(readOnly = false)
	public String saveShoppingCart(ShoppingCart cart){
		if (StringUtils.isBlank(cart.getId())) {
			cart.setId(IdGen.uuid());
			cart.setCreateBy(cart.getUser());
			cart.setUpdateBy(cart.getUser());
			shoppingCartDao.save(cart);
		}else {
			ShoppingCart oldCart = shoppingCartDao.get(cart.getId());
			oldCart.setNumber(cart.getNumber());
			oldCart.setPrice(cart.getPrice());
			oldCart.setAmount(cart.getAmount());
			oldCart.setDelFlag(cart.getDelFlag());
			shoppingCartDao.save(oldCart);
		}
		return cart.getId();
	}
	
	@Transactional(readOnly = false)
	public void clearShoppingCart(ShoppingCart cart){
		//单个商品移出购物车
		if (StringUtils.isNotBlank(cart.getId())) {
			cart = shoppingCartDao.get(cart.getId());
			cart.setDelFlag(ShoppingCart.DEL_FLAG_DELETE);
			shoppingCartDao.save(cart);
		}else {  //清空购物车
			shoppingCartDao.clearShoppingCart(cart);
		}
	}
	
	/**
	 * 获取用户的收货地址列表
	 * @param user
	 * @return
	 */
	public List<UserAddress> getUserAddressList(User user){
		DetachedCriteria dc = userAddressDao.createDetachedCriteria();
		dc.add(Restrictions.eq(ProductClassify.FIELD_DEL_FLAG, ProductClassify.DEL_FLAG_NORMAL));
		dc.add(Restrictions.eq("user.id", user.getId()));
		dc.addOrder(Order.asc("createDate"));
		return userAddressDao.find(dc);
	}
	
	/**
	 * 获取当前商户的收货时间
	 * @param merchant
	 * @return
	 */
	public ReceiptTime getReceiptTime(Merchant merchant){
		ReceiptTime bean = receiptTimeDao.findByMerchantId(merchant.getId());
		if (bean == null) {
			bean = new ReceiptTime();
		}
		return bean;
	}
	
	/**
	 * 获取订单信息
	 * @param id
	 * @return
	 */
	public com.neusoft.lohas.modules.ivm.entity.order.Order getOrder(String id){
		return orderDao.get(id);
	}
	
	/**
	 * 提交订单
	 * @param order
	 */
	@Transactional(readOnly = false)
	public void saveOrder(com.neusoft.lohas.modules.ivm.entity.order.Order order){
		orderDao.save(order);
	}
	
	/**
	 * 获取订单信息
	 * @param orderNo
	 * @return
	 */
	public com.neusoft.lohas.modules.ivm.entity.order.Order findByOrderNo(String orderNo){
		return orderDao.findByOrderNo(orderNo);
	}
	
	/**
	 * 更新支付状态
	 * @param order
	 * @return
	 */
	@Transactional(readOnly = false)
	public void updateOrderStatus(com.neusoft.lohas.modules.ivm.entity.order.Order order){
		com.neusoft.lohas.modules.ivm.entity.order.Order bean = this.findByOrderNo(order.getOrderNo());
		bean.setTradeNo(order.getTradeNo());
		bean.setPayStatus(order.getPayStatus());
		bean.setPayDate(new Date());
		orderDao.save(bean);
	}
	
	/**
	 * 创建查询的DetachedCriteria
	 * @param order
	 * @param type
	 * @return
	 */
	public DetachedCriteria createDetachedCriteria(com.neusoft.lohas.modules.ivm.entity.order.Order order, int type){
		DetachedCriteria dc = orderDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", order.getUser().getId()));
		if(type==0){
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.ne("orderType", String.valueOf(OrderTypeEnum.DELIVERIED.getType())));
		}else if (type==1) { //全部
			
		}else if (type==2) { //待付款
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())));
			dc.add(Restrictions.and(
				Restrictions.or(
					Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType())),
					Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType())),
					Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType())),
					Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
				)
			));
		}else if (type==3) { //待发货
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType())));
			dc.add(Restrictions.and(
				Restrictions.or(
					Restrictions.and(
						Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
					),
					Restrictions.and(
						Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.PAYED.getStatus())),
						Restrictions.or(
							Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType()))
						),
						Restrictions.or(
							Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType()))
						),
						Restrictions.or(
							Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType()))
						)
					)
				)
			));
		}else if (type==4) { //待收货
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERYING.getType())));
		}else if (type==5) { //已完成
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERIED.getType())));
		}else if (type==6) { //已取消
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_DELETE));
		}else if(type==7){//采配中（待发货+待收货）
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
			dc.add(Restrictions.and(
				Restrictions.or(
					Restrictions.and(
						Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType())),
						Restrictions.and(
							Restrictions.or(
								Restrictions.and(
									Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())),
									Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
								),
								Restrictions.and(
									Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.PAYED.getStatus())),
									Restrictions.or(
										Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType()))
									),
									Restrictions.or(
										Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType()))
									),
									Restrictions.or(
										Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType()))
									)
								)
							)
						)
					),
					Restrictions.and(
						Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERYING.getType()))
					)
				)
			));
		}
		dc.addOrder(org.hibernate.criterion.Order.desc("createDate"));
		dc.addOrder(org.hibernate.criterion.Order.asc("payStatus"));
		dc.addOrder(org.hibernate.criterion.Order.asc("orderType"));
		return dc;
	}
	
	/**
	 * 我的订单列表-分页查询
	 * @param page
	 * @param order
	 * @param type
	 * @return
	 */
	public Page<com.neusoft.lohas.modules.ivm.entity.order.Order> findMyOrderList(Page<com.neusoft.lohas.modules.ivm.entity.order.Order> page, com.neusoft.lohas.modules.ivm.entity.order.Order order, int type) {
		return orderDao.find(page, this.createDetachedCriteria(order, type));
	}
	
	/**
	 * 我的订单列表
	 * @param order
	 * @param type
	 * @return
	 */
	public List<com.neusoft.lohas.modules.ivm.entity.order.Order> findMyOrderList(com.neusoft.lohas.modules.ivm.entity.order.Order order, int type) {
		return orderDao.find(this.createDetachedCriteria(order, type));
	}
	
	public long findMyOrderCount(com.neusoft.lohas.modules.ivm.entity.order.Order order, int type) {
		return orderDao.count(this.createDetachedCriteria(order, type));
	}
	
	public ProductClassify findProductClassify(String classifyId){
		return productClassifyDao.get(classifyId);
	}

	/*
	 * 更新用户领奖状态
	 */
	@Transactional(readOnly = false)
	public void updateScanType(String mobile, int type) {
		orderDao.updateScanType(mobile, type);
	}

	/**
	 * 获取当日订单总数
	 * @return
	 */
	public int getOrderNumsByDate(String merchantId) {
		return orderDao.getOrderNumsByDate(merchantId);
	}
	
	@Transactional(readOnly = false)
	public void updateActivityProductNumbers(List<ActivityProduct> list){
		activityProductService.save(list);
	}
	
	@Transactional(readOnly = false)
	public int updateOrderStatusByTimer(){
		String sql = "update ivm_order set del_flag='1' where del_flag='0' and pay_status<>'1' and pay_type<>'1' and create_date is not null and date_add(create_date, INTERVAL 30 MINUTE)<=now()";
		return orderDao.updateBySql(sql, new Parameter());
	}
	
}
